package com.lp.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.ModelAndView;

import com.lp.bo.UserInfoBO;
import com.lp.cache.CacheName;
import com.lp.cache.ProCacheUtil;
import com.lp.service.BaseService;
import com.lp.util.ExcelUtil;
import com.lp.util.ObjectUtil;
import com.lp.util.ResultMapUtils;



public class BaseController extends ResultMapUtils {

	@Autowired
	@Qualifier(value = "baseService")
	protected BaseService service;


	/**
	 * LOG
	 */
	protected final static Logger LOGGER = LoggerFactory.getLogger(BaseController.class);
	
	/**
	 * 根据userKey获取用户信息
	 */
	protected UserInfoBO getUserInfoByUserKey(String userKey){
		return ProCacheUtil.getCache(CacheName.USERINFO, userKey, new UserInfoBO());
	}
	/**
	 * 根据session获取用户信息
	 * @param req
	 * @return
	 */
	protected UserInfoBO getUserInfoBySession(HttpServletRequest req) {
		return (UserInfoBO) req.getSession().getAttribute("user");
	}
	
	/**
	 * 判断是否为用户角色
	 */
	protected Boolean verifyUserRole(String userKey,Integer userTypeCode){
		UserInfoBO user = getUserInfoByUserKey(userKey) ;
		if(ObjectUtil.isEmpty(user)){
			return false ;
		}else{
			if(ObjectUtil.isEmpty(userTypeCode)){
				return true ;
			}
			if(userTypeCode+0 == user.getType()){
				return true ;
			}else{
				return false ;
			}
		}
	}
	
	/**
	 * 判断是否有页面或者数据的访问权限
	 */
	protected ModelAndView accessFilter(String userKey,String url,HttpServletResponse response){
		Map<String, Object> resultMap = getResultMap();
		return getModelAndView(response, resultMap);
	}
	
	/**
	 * Excel 下载
	 */
	protected void downExcel(String mapper,String name,String template,Object param,HttpServletResponse response) {
		List<?> list = (List<?>) getData(service.selectList(mapper , param)) ;
		if(ObjectUtil.isEmpty(list) ||  list.size() > 5000 ){
			list = new ArrayList<>();
		}
		ExcelUtil.exportExcel(name, template, list, response);
	}
}
